import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:fluttertoast/fluttertoast.dart';

import '../../services/screen_adapter.dart';
import '../../widget/mq_button.dart';
import '../../model/product_content.dart';
import '../../config/config.dart';
import '../../services/event_bus.dart';
import './cart_num.dart';
import '../../services/cart_service.dart';
import '../../provider/cart.dart';

class ProductContentFirst extends StatefulWidget {

  final List _productContentList;

  ProductContentFirst(this._productContentList, {Key key}) : super(key: key);

  _ProductContentFirstState createState() => _ProductContentFirstState();
}

class _ProductContentFirstState extends State<ProductContentFirst> {

  ProductContentItem _productContent;
  List _attr = [];
  String _selectedValue;
  var _actionEventBus;

  @override
  void initState() { 
    super.initState();
    _productContent = widget._productContentList[0];
    _attr = _productContent.attr;
    _initAttr();
    ///初始化已选
    _getSelectedAttrValue();

    /// 监听广播
    /// 监听所有广播
    /// eventBus.on().listen((event) {
    ///   print(event.str);
    /// });
    _actionEventBus = eventBus.on<ProductContentEvent>().listen((str) {
      // print(str);
      _attrBottomSheet();
    });

  }

  /// 销毁时，取消事件监听
  void dispose() {
    super.dispose();
    _actionEventBus.cancel();
  }

  /// 初始化Attr格式化数据
  _initAttr() {
    var attr = _attr;
    for (var i=0;i<attr.length;i++) {

      /// 清空数组里面的数据
      attr[i].attrList.clear();

      for(var j=0;j<attr[i].list.length;j++) {
        if (j == 0) {
          attr[i].attrList.add({
            'title': attr[i].list[j],
            'checked': true
          });
        } else {
          attr[i].attrList.add({
            'title': attr[i].list[j],
            'checked': false
          });
        }
        
      }
    }

  }

  /// 改变属性值
  _changeAttr(cate, title, setBottomState) {
    var attr = _attr;
    for(var i=0; i<attr.length; i++) {
      if (attr[i].cate == cate) {
        for(var j=0; j<attr[i].attrList.length; j++) {
          attr[i].attrList[j]['checked'] = false;
          if(attr[i].attrList[j]['title'] == title) {
            attr[i].attrList[j]['checked'] = true;
          }
        }

      }
      
    }
    setBottomState(() { //注意：改变showModalBottomSheet里面的数据，来源于StatefulBuilder
      _attr = attr;
    });

    _getSelectedAttrValue();
  }

  /// 获取选中的值
  _getSelectedAttrValue() {
    var _list = _attr;
    List tempArr = [];
    for(var i=0; i<_list.length; i++) {
      for(var j=0; j<_list[i].attrList.length; j++) {
        if(_list[i].attrList[j]['checked']) {
          tempArr.add(_list[i].attrList[j]['title']);
        }
      }
    }
    
    setState(() {
      _selectedValue = tempArr.join(',');
      ///给筛选属性赋值
       _productContent.selectedAttr = _selectedValue;
    });
  }

  List<Widget> _getAttrItemWidget(attrItem, setBottomState) {
    
     List<Widget> itemList = [];

      attrItem.attrList.forEach((item){
        itemList.add( Container(
          margin: EdgeInsets.all(10),
          child: InkWell(
            onTap: (){
              _changeAttr(attrItem.cate, item['title'], setBottomState);
            },
            child: Chip(
              label: Text("${item['title']}", style: TextStyle(
                color: item['checked'] ? Colors.white : Colors.black54
              )),
              padding: EdgeInsets.all(10),
              backgroundColor: item['checked'] ? Colors.red : Colors.black26
            )
          )
        ));
      });

    return itemList;
  }

  /// 封装一个组件 渲染attr
  List<Widget> _getAttrWidget(setBottomState) {

    List<Widget> attrList = [];

    _attr.forEach((attrItem){
      attrList.add(Wrap(
        children: <Widget>[
          Container(
            width: ScreenAdapter.width(120),
            child: Padding(
              padding: EdgeInsets.only(
                top: ScreenAdapter.height(30)
              ),
              child: Text("${attrItem.cate}: ",
                  style: TextStyle(
                      fontWeight: FontWeight.bold)),
            ),
          ),
          Container(
            width: ScreenAdapter.width(600),
            child: Wrap(
              children: _getAttrItemWidget(attrItem, setBottomState)
            )
          )
        ]
      ));
    });

    return attrList;
  }

  /// 底部弹出框
  _attrBottomSheet() {
    showModalBottomSheet(
        context: context,
        builder: (contex) {
          // showModalBottomSheet相当于另一个组件了，需要通过StatefulBuilder的setState才能改变状态
          return StatefulBuilder( 
            builder: (BuildContext context, setBottomState) {
              return GestureDetector(
                //解决showModalBottomSheet点击消失的问题
                behavior: HitTestBehavior.opaque, // 配置点击不穿透
                onTap: () {
                  return false;
                },
                child: Stack(
                  children: <Widget>[
                    Container(
                      padding: EdgeInsets.all(ScreenAdapter.width(15)),
                      child: ListView(
                        children: <Widget>[
                          Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: _getAttrWidget(setBottomState)
                          ),
                          Divider(),
                          Container(
                            margin: EdgeInsets.only(top: 10),
                            height: ScreenAdapter.height(80),
                            child: Row(
                              children: <Widget>[
                                Text("数量: ", style: TextStyle(fontWeight: FontWeight.bold)),
                                SizedBox(width: 10),
                                CartNum(_productContent)
                              ],
                            ),
                          )
                        ],
                      ),
                    ),
                    Positioned(
                      bottom: 0,
                      width: ScreenAdapter.width(750),
                      height: ScreenAdapter.height(76),
                      child: Row(
                        children: <Widget>[
                          Expanded(
                            flex: 1,
                            child: Container(
                              margin: EdgeInsets.fromLTRB(10, 0, 0, 0),
                              child: MqButton(
                                color: Color.fromRGBO(253, 1, 0, 0.9),
                                text: "加入购物车",
                                callback: () async{
                                  await CartService.addCart(_productContent);
                                  /// 关闭底部筛选属性
                                  Navigator.of(context).pop();
                                  /// 调用provider更新数据
                                  context.read<Cart>().updateList();

                                  Fluttertoast.showToast(
                                    msg: "加入购物车成功",
                                    toastLength: Toast.LENGTH_SHORT,
                                    gravity: ToastGravity.CENTER,
                                    timeInSecForIosWeb: 1,
                                    backgroundColor: Colors.grey[600],
                                    textColor: Colors.white,
                                    fontSize: 16.0
                                  );

                                }
                              )
                            )
                          ),
                          Expanded(
                            flex: 1,
                            child: Container(
                              margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
                              child: MqButton(
                                color: Color.fromRGBO(255, 165, 0, 0.9),
                                text: "立即购买",
                                callback: () {
                                  print('立即购买');
                                },
                              )
                            )
                          )
                        ]
                      ),
                    )
                  ],
                ),
              );
            }
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    ScreenAdapter.init();

    String pic = _productContent.pic;
    pic = Config.domain + pic.replaceAll('\\', '/');

    return Container(
      padding: EdgeInsets.all(10),
      child: ListView(
        children: <Widget>[
          AspectRatio(
            aspectRatio: 16 / 12,
            child: Image.network("$pic",
                fit: BoxFit.cover),
          ),
          //标题
          Container(
            padding: EdgeInsets.only(top: 10),
            child: Text("${_productContent.title}",
                style: TextStyle(
                    color: Colors.black87, fontSize: ScreenAdapter.size(36))),
          ),
          Container(
              padding: EdgeInsets.only(top: 10),
              child: Text(
                  "${_productContent.subTitle}",
                  style: TextStyle(
                      color: Colors.black54,
                      fontSize: ScreenAdapter.size(28)))),
          //价格
          Container(
            padding: EdgeInsets.only(top: 10),
            child: Row(
              children: <Widget>[
                Expanded(
                  flex: 1,
                  child: Row(
                    children: <Widget>[
                      Text("特价: "),
                      Text("¥${_productContent.price}",
                          style: TextStyle(
                              color: Colors.red,
                              fontSize: ScreenAdapter.size(46))),
                    ],
                  ),
                ),
                Expanded(
                  flex: 1,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: <Widget>[
                      Text("原价: "),
                      Text("¥${_productContent.oldPrice}",
                          style: TextStyle(
                              color: Colors.black38,
                              fontSize: ScreenAdapter.size(28),
                              decoration: TextDecoration.lineThrough)),
                    ],
                  ),
                )
              ],
            ),
          ),
          //筛选
          _attr.isNotEmpty ? Container(
            margin: EdgeInsets.only(top: 10),
            height: ScreenAdapter.height(80),
            child: InkWell(
              onTap: () {
                _attrBottomSheet();
              },
              child: Row(
                children: <Widget>[
                  Text("已选: ", style: TextStyle(fontWeight: FontWeight.bold)),
                  Text("$_selectedValue")
                ],
              )
            ),
          ) : Text(''),
          Divider(),
          Container(
            height: ScreenAdapter.height(80),
            child: Row(
              children: <Widget>[
                Text("运费: ", style: TextStyle(fontWeight: FontWeight.bold)),
                Text("免运费")
              ],
            ),
          ),
          Divider(),
        ],
      ),
    );
  }
}